  
  
/*  
* Copyright @ 2017 com.iflysse.trains  
* xebest-erp 下午4:34:45  
* All right reserved.  
*  
*/  
  
package com.xebest.web.service.impl;  

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.xebest.common.enums.erp.storehouse.VenStoreDeliveryTypeEnum;
import com.xebest.util.seq.StoreHouseSeqUtil;
import com.xebest.web.form.XeVenStoreInvForm;
import com.xebest.web.mapper.read.XeVenStoreInventoryDetailReadMapper;
import com.xebest.web.mapper.read.XeVenStoreInventoryReadMapper;
import com.xebest.web.mapper.write.XeVenStoreInventoryDetailWriteMapper;
import com.xebest.web.mapper.write.XeVenStoreInventoryWriteMapper;
import com.xebest.web.model.XeVenStoreDelivDetailEntity;
import com.xebest.web.model.XeVenStoreDeliveryEntity;
import com.xebest.web.model.XeVenStoreInventoryDetailEntity;
import com.xebest.web.model.XeVenStoreInventoryEntity;
import com.xebest.web.model.XeVenStoreStockEntity;
import com.xebest.web.service.XeVenStoreInventoryService;
import com.xebest.web.view.ErpUserInfo;
import com.xebest.web.view.XeVenStoreInvProView;
import com.xebest.web.view.XeVenStoreInventoryView;

  
/**  
 * @desc: xebest-erp  
 * @author: 杜春静 
 * @createTime: 2017年6月22日 下午4:34:45  
 * @history:  
 * @version: v1.0    
*/  
@Service  
public class XeVenStoreInventoryServiceImpl implements XeVenStoreInventoryService {
	
	private static final Logger log = LoggerFactory.getLogger(XeVenStoreInventoryService.class);//日志记录类
	
	@Autowired
	XeVenStoreInventoryWriteMapper  xeVenStoreInventoryWriteMapper;//库存一览的写Mapper
	
	@Autowired
	XeVenStoreInventoryReadMapper   xeVenStoreInventoryReadMapper; //库存一览的读Mapper
	
	@Autowired
	XeVenStoreInventoryDetailWriteMapper storeInvDetailWriteMapper;//库存一览的商品明细写Mapper
	@Autowired
	XeVenStoreInventoryDetailReadMapper storeInvDetailReadMapper;//库存一览的商品明细读Mapper
	/**
	 * 查询库存一览列表
	 * @author: 杜春静  
	 * @createTime: 2017年6月22日 下午4:09:08  
	 * @history:  
	 * @param params
	 * @return List<XeVenStoreInventoryEntity>
	 */  
	@Override
	public List<XeVenStoreInventoryView> queryStoreInvList(
			Map<String, Object> params)  {
		  log.info("调用查询库存一览列表的sql");
		//按条件查询仓库一览表 
		return xeVenStoreInventoryReadMapper.listStoreInvByForm(params);
		
	}


	/*  
	 * 更改单个库存上下限
	 *(non-Javadoc)  
	 * @see com.xebest.web.service.XeVenStoreInventoryService#updateStoreInv(com.xebest.web.form.XeVenStoreInvForm)  
	*/  
	@Override
	public int updateStoreInv(XeVenStoreInvForm form,ErpUserInfo userInfo) throws Exception {
		 
		//封装库存一览数据
		XeVenStoreInventoryEntity record = new  XeVenStoreInventoryEntity();
		record.setStoreInvId(form.getStoreInvId());
		record.setInvMax(form.getInvMax());
		record.setInvMin(form.getInvMin());
		record.setUserCode(userInfo.getUserCode());
		record.setModifyUser(userInfo.getLoginName());
		
		return xeVenStoreInventoryWriteMapper.updateStoreInvByStoreInv(record);  
		
	}
	  
	/**
	 * 查询仓库库存
	 * @author: 杜春静  
	 * @createTime: 2017年6月29日 下午2:55:03  
	 * @history:  
	 * @param record
	 * @return XeVenStoreInventoryEntity
	 */
	@Override
	public XeVenStoreInventoryEntity getStoreInvByParam(
			XeVenStoreInventoryEntity record) {
		  
		return xeVenStoreInventoryWriteMapper.getStoreInvByParam(record);  
		
	}


	  
	/**
	 * 更新仓库的库存数量
	 * @author: 杜春静  
	 * @createTime: 2017年6月29日 下午2:59:09  
	 * @history:  
	 * @param record
	 * @return int
	 * @throws Exception 
	 */
	@Override
	public int updateStoreInvByStoreInventoryEntity(XeVenStoreInventoryEntity record,BigDecimal saleNum) throws Exception {
		  
		return xeVenStoreInventoryWriteMapper.updateStoreInvByMap(record,saleNum);  
		
	}


	  
	/**
	 * 添加库存一览
	 * @author: 杜春静  
	 * @createTime: 2017年6月30日 下午3:01:05  
	 * @history:  
	 * @param record
	 * @return int
	 * @throws Exception 
	 */
	@Override
	public int saveStoreInv(XeVenStoreInventoryEntity record) throws Exception {
		int result = 0;
		//如果必要参数为空，直接返回
		if(record.getStoreId() == null ||record.getProSku()== null){
			return result;
		}
		//根据（sku,pro,userCode）查询是否有库存
		XeVenStoreInventoryEntity resultInvEntity = xeVenStoreInventoryWriteMapper.getStoreInvByParam(record);
		//如果商品入库过
		if(resultInvEntity != null){
			//添加本次入库批次
			List<XeVenStoreInventoryDetailEntity> detailList = record.getStoreInvDetailList();
			if(null != detailList && detailList.size() > 0){
				for(XeVenStoreInventoryDetailEntity entity:detailList){
					entity.setStoreInvId(resultInvEntity.getStoreInvId());
					log.info("更新库存一览storeInvId为{}中的实际库存{}",entity.getStoreInvId(),record.getActualInv());
					result = xeVenStoreInventoryWriteMapper.updateStoreInvByMap(record,null);
				}
				if(result >0){
					//添加入库批次
					result=storeInvDetailWriteMapper.batchInsertStoreInvDetail(detailList);
					log.info("批量添加库存一览的入库明细,总共有{}条数据，执行结果为{},",detailList.size(),result);
				}
			}
		 } else {
			//库存监控业务标识 
				String storeInvId = StoreHouseSeqUtil.seqUtils.createStoreinvIdNo(); 
				record.setStoreInvId(storeInvId);
				//添加库存一览主表信息
				log.info("添加库存一览主表,数据为：{}",JSON.toJSONString(record));
				result = xeVenStoreInventoryWriteMapper.insertXeVenStoreInv(record);
				
				//获取库存一览的商品明细
				List<XeVenStoreInventoryDetailEntity> detailList = record.getStoreInvDetailList();
				//如果库存一览的商品明细不为空并且主表添加成功，则添加库存一览的商品明细
				if(null!=detailList&& detailList.size()>0 && result >0){
					//设置库存一览的商品的明细的主表业务标识
					for(XeVenStoreInventoryDetailEntity entity:detailList){
						entity.setStoreInvId(storeInvId);
					}
					//批量添加入库批次商品明细
					result=storeInvDetailWriteMapper.batchInsertStoreInvDetail(detailList);
					log.info("批量添加库存一览的入库明细,总共有{}条数据，执行结果为{},",detailList.size(),result);
				}
		 }
		
		return result;
	}
	
	/**
	 * 如果初始化
	 * @author: 杜春静  
	 * @createTime: 2017年8月23日 下午3:45:03  
	 * @history:  
	 * @param record
	 * @return
	 * @throws Exception int
	 */
	public int initStoreInv(XeVenStoreInventoryEntity record) throws Exception {
		int result = 0;
		//如果必要参数为空，直接返回
		if(StringUtils.isEmpty(record.getStoreId())  || StringUtils.isEmpty(record.getProSku() )|| StringUtils.isEmpty(record.getUserCode())){
			return result;
		}
		//根据（sku,pro,userCode）查询是否有库存
		XeVenStoreInventoryEntity resultInvEntity = xeVenStoreInventoryWriteMapper.getStoreInvByParam(record);
		//如果商品入库过
		if(resultInvEntity == null){
		    //库存监控业务标识 
			String storeInvId = StoreHouseSeqUtil.seqUtils.createStoreinvIdNo(); 
			record.setStoreInvId(storeInvId);
			//添加库存一览主表信息
			result = xeVenStoreInventoryWriteMapper.insertXeVenStoreInv(record);
		 } else if(resultInvEntity != null){
			// resultInvEntity.setTransitInv(record.getTransitInv());//增加在途数
			 result = xeVenStoreInventoryWriteMapper.updateStoreInvByMap(record,null);
		 }
		
		return result;
	}

	  
	/**
	 * 出库时，根据备货信息，更新库存一览明细记录
	 * @author: 杜春静  
	 * @createTime: 2017年7月4日 下午3:26:45  
	 * @history:  
	 * @param storeStockList
	 * @param delivType
	 * @return
	 * @throws Exception int
	 */
	@Override
	public int updateStoreInvAndDetailByStoreStock(
			List<XeVenStoreStockEntity> storeStockList,Integer delivType)
			throws Exception {
		  int result = 0;
		for(XeVenStoreStockEntity storeStock : storeStockList){
				// 更新库存批次实际库存-
				XeVenStoreInventoryDetailEntity invDetail = new XeVenStoreInventoryDetailEntity();
				invDetail.setProSku(storeStock.getProSku());
				invDetail.setBatchNo(storeStock.getReceiptBacthNo());//备货时的入库批次
				BigDecimal actualInv = storeStock.getStockNums().multiply(new BigDecimal(-1));
				invDetail.setActualInv(actualInv.setScale(2, BigDecimal.ROUND_HALF_UP));
				invDetail.setModifyUser(storeStock.getModifyUser());
				result = storeInvDetailWriteMapper.updateStoreInvDetailByMap(invDetail);
				log.info("根据 receiptBatchNo:{}, proSku: {}更新仓库的入库批次详情，批次的实际库存减少{}",storeStock.getReceiptBacthNo(),
						storeStock.getProSku(), storeStock.getStockNums());
			
		}
		return 	result;  
		
	}
	/**
	 * 根据出库更新库存一览
	 * @author: 杜春静  
	 * @createTime: 2017年8月30日 下午6:37:26  
	 * @history:  
	 * @param delivEntity
	 * @return
	 * @throws Exception int
	 */
	public int updateStoreInvAndDetailByDeliv(XeVenStoreDeliveryEntity delivEntity) throws Exception{
		int result = 0;
		List<XeVenStoreDelivDetailEntity> delivDetailList = delivEntity.getDelivDtailList();
		Integer delivType = delivEntity.getDeliveryType();
		for(XeVenStoreDelivDetailEntity delivDetail : delivDetailList){
			//更新库存主表的实际库存- 占用库存-
			XeVenStoreInventoryEntity invEntity = new XeVenStoreInventoryEntity();
			invEntity.setUserCode(delivEntity.getUserCode());
			invEntity.setStoreId(delivEntity.getStoreId());
			invEntity.setProSku(delivDetail.getProSku());
			invEntity.setModifyUser(delivEntity.getModifyUser());
			BigDecimal actualInv = delivDetail.getProOutNum().multiply(new BigDecimal(-1));
			invEntity.setActualInv(actualInv.setScale(2, BigDecimal.ROUND_HALF_UP));
			if(delivType.equals(VenStoreDeliveryTypeEnum.SALES_DELIVERY.getValue())){
				BigDecimal lockedInv = delivDetail.getPlanOutNum().multiply(new BigDecimal(-1));
				invEntity.setLockedInv(lockedInv.setScale(2, BigDecimal.ROUND_HALF_UP));
			}
			log.info("根据 userCode:{}, storeId:{}, proSku{}更新库存一览主表，实际库存减少{},占用库存减少{}",delivEntity.getUserCode(),
					delivEntity.getStoreId(), delivDetail.getProSku(),delivDetail.getProOutNum(),delivDetail.getPlanOutNum());
			result = xeVenStoreInventoryWriteMapper.updateStoreInvByMap(invEntity, null);
		}
		
		return result;
	}
	  
	/*  
	 * 查询库存商品列表
	 *(non-Javadoc)  
	 * @see com.xebest.web.service.XeVenStoreInventoryService#queryInvProList(com.xebest.web.form.XeVenStoreInvForm)  
	*/  
	
	@Override
	public List<XeVenStoreInvProView> queryInvProList(
			XeVenStoreInvForm storeInvForm) {
		  
		return xeVenStoreInventoryReadMapper.listInvPro(storeInvForm);  
		
	}


	  
	/* 
	 * 批量更新库存一览，现在只是批量更新采购在途
	 *(non-Javadoc)  
	 * @see com.xebest.web.service.XeVenStoreInventoryService#batchUpdateStoreInv(java.util.List)  
	*/  
	
	@Override
	public int batchUpdateStoreInv(List<XeVenStoreInventoryEntity> params)
			throws Exception {
		  
		  
		return this.xeVenStoreInventoryWriteMapper.batchUpdateStoreInv(params);  
		
	}


	  
	/* 
	 * 批量更新库存上下限 
	 *(non-Javadoc)  
	 * @see com.xebest.web.service.XeVenStoreInventoryService#batchUpdateInvLimit(java.util.Map)  
	*/  
	
	@Override
	public int batchUpdateInvLimit(Map<String, Object> params) throws Exception {
		  
		return this.xeVenStoreInventoryWriteMapper.batchUpdateInvLimit(params);  
		
	}

	@Override
	public BigDecimal queryStockCost(Map<String, Object> map) {
		return storeInvDetailReadMapper.queryStockCost(map); 
	}
	  
	
	

}
  
